package cn.io.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author summit
 * @since 2022/5/11 11:23
 */
public class FileNio {

	public static void main(String[] args) throws IOException {
		//write();

		read();
	}

	private static void write() throws IOException {
		File file = new File("nio.txt");
		FileOutputStream os = new FileOutputStream(file);
		FileChannel channel = os.getChannel();
		ByteBuffer bb = ByteBuffer.allocate(1024);
		bb.put("hello word!".getBytes());
		bb.flip();
		channel.write(bb);
		os.close();
	}

	private static void read() throws IOException {
		File file = new File("nio.txt");
		FileInputStream fis = new FileInputStream(file);
		FileChannel channel = fis.getChannel();
		ByteBuffer bb = ByteBuffer.allocate((int) file.length());

		channel.read(bb);
		System.out.println(new String(bb.array()));
		fis.close();
	}
}
